package com.im.controller;

import com.im.MDA;
import com.im.service.common.dao.IFileOperDAO;
import com.im.service.common.dao.IFileQueryDAO;
import com.im.service.common.smo.ICommonSMO;
import com.im.service.contract.dao.IContractOperDAO;
import com.im.service.docManage.smo.IDocManageQuerySMO;
import com.im.service.docReview.smo.IDocReviewQuerySMO;
import com.im.service.dto.*;
import com.im.service.model.NoticeManageVo;
import com.im.service.noticeManage.smo.INoticeManageOperSmo;
import com.im.service.noticeManage.smo.INoticeManageQuerySmo;
import com.im.service.projectInfo.smo.IProjectInfoQuerySMO;
import com.im.service.purchasePlan.smo.IPurchasePlanQuerySMO;
import com.im.service.result.smo.IResultOperSMO;
import com.im.service.result.smo.IResultQuerySMO;
import com.im.service.tenderInfo.smo.ITenderInfoQuerySMO;
import com.im.util.ListUtil;
import com.im.util.ReturnsUtil;
import com.im.util.StringUtil;
import com.im.viewmodel.noticeManageView.QueryNoticeManageListForUIVo;
import net.sf.json.JSONObject;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * 中标通知书后端服务.

 * @author wangxh
 * 2018年3月21日
 */
@RestController
@RequestMapping("/noticeManageService")
public class NoticeManageService {

    private static final Logger logger = LogManager.getLogger(NoticeManageService.class);

    @Autowired
    private INoticeManageQuerySmo noticeManageQuerySmo;
    @Autowired
    private INoticeManageOperSmo noticeManageOperSmo;
    @Autowired
    private IPurchasePlanQuerySMO purchasePlanQuerySMO;
    @Autowired
    private IProjectInfoQuerySMO projectInfoQuerySMO;
    @Autowired
    private IResultQuerySMO resultQuerySMO;
    @Autowired
    private IResultOperSMO resultOperSMO;
    @Autowired
    private ITenderInfoQuerySMO tenderInfoQuerySMO;
    @Autowired
    private IDocManageQuerySMO docManageQuerySMO;
    @Autowired
    private IDocReviewQuerySMO docReviewQuerySMO;
    @Autowired
    private IFileOperDAO fileOperDAO;
    @Autowired
    private IFileQueryDAO fileQueryDAO;
	@Autowired
	private IContractOperDAO contractOperDAO;
	@Autowired
	private ICommonSMO commonSMO;


    /**
     * 中标通知书列表查询.
     *
     * @param jsonStr
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/queryNoticeManageList")
    public String queryNoticeManageList(@RequestBody String jsonStr){
        if (logger.isInfoEnabled()) {
            logger.info("请求入参json:{}", jsonStr);
        }

        try {
            if (jsonStr == null || jsonStr.length() <= 0) {
                throw new BaseException("请求入参为空，请核查数据!");
            }

            PageQuery<NoticeManage> result = noticeManageQuerySmo.queryNoticeManageList(jsonStr,null);
            logger.info("请求出参json:{}", JSONObject.fromObject(ReturnsUtil.returnSuccess(result)).toString());
            return ReturnsUtil.returnSuccess(result).toString();
        } catch (Exception e) {
            if (logger.isErrorEnabled()) {
                logger.error(ReturnsUtil.getStackTrackMessage(e));
            }
            return ReturnsUtil.returnFailure(e.getMessage()).toString();
        }
    }

    /**
     * 中标通知书列表页面查询.
     *
     * @param jsonStr
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/queryNoticeManageListForUI")
    public String queryNoticeManageListForUI(@RequestBody String jsonStr){
        if (logger.isInfoEnabled()) {
            logger.info("请求入参json:{}", jsonStr);
        }
        try {
            if (jsonStr == null || jsonStr.length() <= 0) {
                throw new BaseException("请求入参为空，请核查数据!");
            }

            PageQuery<QueryNoticeManageListForUIVo> QueryNoticeManageListForUIVoQuery = new PageQuery<QueryNoticeManageListForUIVo>();
            Map<String,Object> reqMap = new HashMap<String,Object>();
            JSONObject inJson = JSONObject.fromObject(jsonStr);
            if(inJson.containsKey("orgId")){
                if(null!=inJson.getString("orgId")&&!"".equals(inJson.getString("orgId"))){
                    reqMap.put("orgId",inJson.getString("orgId"));
                    reqMap.put("developOrg",inJson.getString("orgId"));
                }
            }
            if(inJson.containsKey("planProjClass")){
                if(null!=inJson.getString("planProjClass")&&!"".equals(inJson.getString("planProjClass"))){
                    reqMap.put("planProjClass",inJson.getString("planProjClass"));
                }
            }
            if(inJson.containsKey("implProjectId")){
                if(null!=inJson.getString("implProjectId")&&!"".equals(inJson.getString("implProjectId"))){
                    reqMap.put("impleProjId",inJson.getString("implProjectId"));
                }
            }

            if(inJson.containsKey("statusCdQry")){
                if(null!=inJson.getString("statusCdQry")&&!"".equals(inJson.getString("statusCdQry"))){
                    reqMap.put("statusCdQry",inJson.getString("statusCdQry"));
                }
            }
            //1.获取招标成功的招标信息
            List<TenderInfo> tenderInfos = tenderInfoQuerySMO.querySuccTenderInfoList(reqMap);
//            List<TenderInfo> tenderInfos = page.getRows();
            List<QueryNoticeManageListForUIVo>  queryNoticeManageListForUIVos = new ArrayList<QueryNoticeManageListForUIVo>();
            if(!ListUtil.isListEmpty(tenderInfos)){
                for(TenderInfo tenderInfo :tenderInfos){
                    QueryNoticeManageListForUIVo queryNoticeManageListForUIVo = new QueryNoticeManageListForUIVo();
                    //招标信息
                    queryNoticeManageListForUIVo.setTenderInfo(tenderInfo);
                    if(null!=tenderInfo){
                        String docManageId = tenderInfo.getDocManageId();
                        if(null!=docManageId){
                            DocManage docManage = docManageQuerySMO.queryDocManageById(docManageId);
                            queryNoticeManageListForUIVo.setDocManage(docManage);
                            Map<String,Object> par = new HashMap<String,Object>();
                            par.put("docManageId",docManageId);
                            DocReviewResult docReviewResult = docReviewQuerySMO.queryDocReviewResultByDocManageId(par);
                            queryNoticeManageListForUIVo.setDocReviewResult(docReviewResult);
                        }

                        Map<String,Object> para = new HashMap<String,Object>();
                        para.put("uploadObjId",tenderInfo.getTenderInfoId());
                        para.put("uploadObjType","110");
                        List<FileUpload> fileList = fileQueryDAO.queryFileUploadsByCond(para);
                        if(!ListUtil.isListEmpty(fileList)){
                            List<Attachment> attachmentList = new ArrayList<Attachment>();
                            for(FileUpload fileUpload:fileList){
                                Attachment attachment = new Attachment();
                                attachment.setUploadId(fileUpload.getUploadId());
                                attachment.setAttachPath(fileUpload.getFilePath());
                                attachment.setAttachSuffix(fileUpload.getFileSuffix());
                                attachment.setAttachFullName(fileUpload.getUploadName());
                                attachment.setUploadDt(fileUpload.getUploadDate());
                                attachment.setAttachSize(fileUpload.getUploadSize());
                                attachment.setAttachFullName(fileUpload.getUploadName());
                                attachmentList.add(attachment);
                            }
                            queryNoticeManageListForUIVo.setFileList(attachmentList);
                        }
                    }

                    //获取实施项目
                    ImplementProject implementProjectReq  =new ImplementProject();
                    implementProjectReq.setImpleProjId(tenderInfo.getImpleProjId());
                    ImplementProject implementProject =  projectInfoQuerySMO.queryImpleProjDetail(implementProjectReq);
                    if(null!=implementProject){
                        queryNoticeManageListForUIVo.setImplementProject(implementProject);
                        queryNoticeManageListForUIVo.setDevelopOrgId(implementProject.getDevelopOrg());
                        queryNoticeManageListForUIVo.setDevelopOrgName(implementProject.getDevelopOrgName());
                        queryNoticeManageListForUIVo.setDevelopOrgType(implementProject.getDevelopOrgType());
                    }

                    //采购信息
                    String purchPlanId = tenderInfo.getPurchPlanId();
                    if(null!=purchPlanId){
                        //获取采购计划
                        PurchasePlan purchasePlanParam = new PurchasePlan();
                        purchasePlanParam.setPurchPlanId(purchPlanId);
                        PurchasePlan purchasePlan = purchasePlanQuerySMO.queryPurchasePlanDetail(purchasePlanParam);
                        if(null!=purchasePlan){
                            queryNoticeManageListForUIVo.setPurchasePlan(purchasePlan);
                        }
                    }

                    //获取中标结果信息
                    Map<String,Object> param = new HashMap<String,Object>();
                    param.put("tenderInfoId",tenderInfo.getTenderInfoId());
                    List<Result> tresults = resultQuerySMO.queryResultList(param);
                    if(!ListUtil.isListEmpty(tresults)){
                        Result  tresult = tresults.get(0);
                        if(null!=tresult){
                            queryNoticeManageListForUIVo.setOrgId(tresult.getOrgId());
                            queryNoticeManageListForUIVo.setOrgName(tresult.getOrgName());
                            queryNoticeManageListForUIVo.setOrgType(tresult.getOrgType());
                            queryNoticeManageListForUIVo.setMoney(tresult.getMoney());
                            queryNoticeManageListForUIVo.setResult(tresult);

                            //获取通知书信息
                            Map<String,Object> par = new HashMap<String,Object>();
                            par.put("resultId",tresult.getResultId());
                            List<NoticeManage> noticeManages = noticeManageQuerySmo.queryNoticeManageList(par);
                            if(!ListUtil.isListEmpty(noticeManages)){
                                NoticeManage noticeManage = noticeManages.get(0);
                                if(null!=noticeManage){
                                    queryNoticeManageListForUIVo.setNoticeManage(noticeManage);
                                    Map<String,Object> pa = new HashMap<String,Object>();
                                    pa.put("uploadObjId",noticeManage.getNoticeManageId());
                                    pa.put("uploadObjType","110");
                                    List<FileUpload> noticeFileList = fileQueryDAO.queryFileUploadsByCond(pa);
                                    if(!ListUtil.isListEmpty(noticeFileList)) {
                                        FileUpload noticeFile = noticeFileList.get(0);
                                        Attachment attachment = new Attachment();
                                        attachment.setUploadId(noticeFile.getUploadId());
                                        attachment.setAttachPath(noticeFile.getFilePath());
                                        attachment.setAttachSuffix(noticeFile.getFileSuffix());
                                        attachment.setAttachFullName(noticeFile.getUploadName());
                                        attachment.setUploadDt(noticeFile.getUploadDate());
                                        attachment.setAttachSize(noticeFile.getUploadSize());
                                        attachment.setAttachFullName(noticeFile.getUploadName());
                                        queryNoticeManageListForUIVo.setNoticeFile(attachment);
                                    }
                                }
                            }
                        }
                    }
                    queryNoticeManageListForUIVos.add(queryNoticeManageListForUIVo);
                }
            }
            QueryNoticeManageListForUIVoQuery.setRows(queryNoticeManageListForUIVos);
            //logger.info("请求出参json:{}", JSONObject.fromObject(ReturnsUtil.returnSuccess(QueryNoticeManageListForUIVoQuery)).toString());
            return ReturnsUtil.returnSuccess(QueryNoticeManageListForUIVoQuery).toString();
        } catch (Exception e) {
            if (logger.isErrorEnabled()) {
                logger.error(ReturnsUtil.getStackTrackMessage(e));
            }
            return ReturnsUtil.returnFailure(e.getMessage()).toString();
        }
    }

    /**
     *
     * 查询中标通知书详情.
     *
     * @param
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/queryNoticeManageDetail")
    public String queryNoticeManageDetail(@RequestBody NoticeManage noticeManage){
        if (logger.isInfoEnabled()) {
            logger.info("请求入参:{}", noticeManage.toString());
        }
        try {
            if (noticeManage == null || StringUtil.isEmpty(noticeManage.getNoticeManageId())) {
                throw new BaseException("请求入参为空，请核查数据!");
            }
            NoticeManage result = noticeManageQuerySmo.queryNoticeManageDetail(noticeManage);
            //logger.info("请求出参json:{}", JSONObject.fromObject(ReturnsUtil.returnSuccess(result)).toString());
            return ReturnsUtil.returnSuccess(result).toString();
        } catch (Exception e) {
            if (logger.isErrorEnabled()) {
                logger.error(ReturnsUtil.getStackTrackMessage(e));
            }
            return ReturnsUtil.returnFailure(e.getMessage()).toString();
        }
    }


    /**
     *
     *  新增中标通知书信息
     * @param
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/addNoticeManage")
    public String addNoticeManage(@RequestBody NoticeManageVo noticeManage){
        if (logger.isInfoEnabled()) {
            logger.info("请求入参:{}", noticeManage.toString());
        }
        try {
            if (noticeManage == null) {
                throw new BaseException("请求入参为空，请核查数据!");
            }
            //根据tenderInfoId获取中标结果。
            String tenderInfoId = noticeManage.getTenderInfoId();
            Map<String,Object> inMap = new HashMap<String,Object>();
            inMap.put("tenderInfoId",tenderInfoId);
            List<Result> results = resultQuerySMO.queryResultList(inMap);
            String noticeManageId =UUID.randomUUID().toString();
            if(!ListUtil.isListEmpty(results)){
                Result r = results.get(0);
                noticeManage.setResultId(r.getResultId());
                noticeManage.setNoticeManageId(noticeManageId);
                noticeManageOperSmo.addNoticeManage(noticeManage);
                //新增合同
               // TenderInfo tenderInfo = tenderInfoQuerySMO.queryTenderInfoById(tenderInfoId);
                String contractCode = commonSMO.querySeqForRule("4",noticeManage.getImpleProjId());
                String statusCd = noticeManage.getStatusCd();
                if(statusCd != null && "20".equals(statusCd)){
              	  Contract contract = new Contract();
                    contract.setContractId(UUID.randomUUID().toString());
                    contract.setContractCode(contractCode);
                    contract.setResultId(r.getResultId());
                    contract.setOrgId(noticeManage.getOrgId());
                    contract.setImpleProjId(noticeManage.getImpleProjId());
                    contract.setStatusCd("10");
                    contract.setPurchPlanId(noticeManage.getPurchPlanId());
              	  contractOperDAO.insertContract(contract);
                }
                //回填中标结果信息表中的承接商和中标价格
                Result result = new Result();
                result.setResultId(noticeManage.getResultId());
                result.setOrgId(noticeManage.getOrgId());
                result.setMoney(noticeManage.getMoney());
                resultOperSMO.updateResult(result);
                //处理招标文件内容
                List<Attachment> fileList = noticeManage.getFileList();
                if(!ListUtil.isListEmpty(fileList)){
                    for(Attachment attachment : fileList){
                        FileUpload fileUpload = new FileUpload();
                        String uploadType = "";
                        if (attachment.getAttachSuffix() != null && attachment.getAttachSuffix().length() > 0) {
                            uploadType = (String) MDA.FILE_UPLOAD_TYPE.get(attachment.getAttachSuffix().toLowerCase());
                        }
                        String uploadId = UUID.randomUUID().toString();
                        fileUpload.setUploadId(uploadId);
                        fileUpload.setUploadObjType("90");
                        fileUpload.setUploadObjId(tenderInfoId);
                        fileUpload.setUploadType(uploadType);
                        fileUpload.setUploadName(attachment.getAttachFullName());
                        fileUpload.setUploadSize(attachment.getAttachSize());
                        fileUpload.setUploadDate(attachment.getUploadDt());
                        fileUpload.setFilePath(attachment.getAttachPath());
                        fileUpload.setFileSuffix(attachment.getAttachSuffix());
                        fileOperDAO.saveFileUpload(fileUpload);
                    }
                }

                //处理通知书文件
                Attachment noticeFile = noticeManage.getNoticeFile();
                if(null!=noticeFile){
                    FileUpload fileUpload = new FileUpload();
                    String uploadType = "";
                    if (noticeFile.getAttachSuffix() != null && noticeFile.getAttachSuffix().length() > 0) {
                        uploadType = (String) MDA.FILE_UPLOAD_TYPE.get(noticeFile.getAttachSuffix().toLowerCase());
                    }
                    String uploadId = UUID.randomUUID().toString();
                    fileUpload.setUploadId(uploadId);
                    fileUpload.setUploadObjType("90");
                    fileUpload.setUploadObjId(noticeManageId);
                    fileUpload.setUploadType(uploadType);
                    fileUpload.setUploadName(noticeFile.getAttachFullName());
                    fileUpload.setUploadSize(noticeFile.getAttachSize());
                    fileUpload.setUploadDate(noticeFile.getUploadDt());
                    fileUpload.setFilePath(noticeFile.getAttachPath());
                    fileUpload.setFileSuffix(noticeFile.getAttachSuffix());
                    fileOperDAO.saveFileUpload(fileUpload);
                }
            }
            return ReturnsUtil.returnSuccess(new JSONObject()).toString();
        } catch (Exception e) {
            if (logger.isErrorEnabled()) {
                logger.error(ReturnsUtil.getStackTrackMessage(e));
            }
            return ReturnsUtil.returnFailure(e.getMessage()).toString();
        }
    }

    /**
     *
     *  修改中标通知书信息
     * @param noticeManage
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/updateNoticeManage")
    public String updateNoticeManage(@RequestBody NoticeManageVo noticeManage){
        if (logger.isInfoEnabled()) {
            logger.info("请求入参:{}", noticeManage.toString());
        }
        try {
            if (noticeManage == null || StringUtil.isEmpty(noticeManage.getNoticeManageId())) {
                throw new BaseException("请求入参为空，请核查数据!");
            }
            noticeManageOperSmo.updateNoticeManage(noticeManage);
           //新增合同
            String contractCode =commonSMO.querySeqForRule("4",noticeManage.getImpleProjId());
            String statusCd = noticeManage.getStatusCd();
            if(statusCd != null && "20".equals(statusCd)){
                NoticeManage cNoticeManage = noticeManageQuerySmo.queryNoticeManageById(noticeManage.getNoticeManageId());
                Contract contract = new Contract();
                contract.setContractId(UUID.randomUUID().toString());
                contract.setContractCode(contractCode);
                contract.setResultId(cNoticeManage.getResultId());
                contract.setImpleProjId(noticeManage.getImpleProjId());
                contract.setPurchPlanId(noticeManage.getPurchPlanId());
                contract.setOrgId(noticeManage.getOrgId());
                contract.setStatusCd("10");
                contractOperDAO.insertContract(contract);
            }

            return ReturnsUtil.returnSuccess(new JSONObject()).toString();
        } catch (Exception e) {
            if (logger.isErrorEnabled()) {
                logger.error(ReturnsUtil.getStackTrackMessage(e));
            }
            return ReturnsUtil.returnFailure(e.getMessage()).toString();
        }
    }

    /**
     *
     *  修改中标通知书信息
     * @param noticeManage
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/updateNoticeManageByBatch")
    public String updateNoticeManageByBatch(@RequestBody NoticeManageVo noticeManage){
        if (logger.isInfoEnabled()) {
            logger.info("请求入参:{}", noticeManage.toString());
        }
        try {
            if (noticeManage == null) {
                throw new BaseException("请求入参为空，请核查数据!");
            }

            noticeManageOperSmo.updateNoticeManageByBatch(noticeManage);
            List<String> impleProjIds = noticeManage.getImpleProjIds();
            //新增合同
            int i = 0;

            for(String impleProjId:impleProjIds) {
                String contractCode =commonSMO.querySeqForRule("4",impleProjId);
                List<String> noticeManageIds=noticeManage.getNoticeManageIds();
                int j=0;
                String noticeManageId = null;
                for(String noticeManageIdFor:noticeManageIds) {
                     if (i == j) {
                         noticeManageId = noticeManageIdFor;
                         break;
                     }
                     j++;
                }
                if (noticeManageId != null) {
                    NoticeManage cNoticeManage = noticeManageQuerySmo.queryNoticeManageById(noticeManageId);
                    Contract contract = new Contract();
                    contract.setContractId(UUID.randomUUID().toString());
                    contract.setContractCode(contractCode);
                    contract.setResultId(cNoticeManage.getResultId());
                    contract.setImpleProjId(impleProjId);
                    contract.setPurchPlanId(cNoticeManage.getPurchPlanId());
                    contract.setStatusCd("10");
                    contractOperDAO.insertContract(contract);
                }
                i ++;
            }
            return ReturnsUtil.returnSuccess(new JSONObject()).toString();
        } catch (Exception e) {
            if (logger.isErrorEnabled()) {
                logger.error(ReturnsUtil.getStackTrackMessage(e));
            }
            return ReturnsUtil.returnFailure(e.getMessage()).toString();
        }
    }

    /**
     *
     *  删除中标通知书信息
     * @param noticeManage
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/deleteNoticeManage")
    public String deleteNoticeManage(@RequestBody NoticeManageVo noticeManage){
        if (logger.isInfoEnabled()) {
            logger.info("请求入参:{}", noticeManage.toString());
        }
        try {
            if (noticeManage == null || StringUtil.isEmpty(noticeManage.getNoticeManageId())) {
                throw new BaseException("请求入参为空，请核查数据!");
            }
            noticeManageOperSmo.deleteNoticeManage(noticeManage);
            return ReturnsUtil.returnSuccess(new JSONObject()).toString();
        } catch (Exception e) {
            if (logger.isErrorEnabled()) {
                logger.error(ReturnsUtil.getStackTrackMessage(e));
            }
            return ReturnsUtil.returnFailure(e.getMessage()).toString();
        }
    }
}
